package com.student.dms;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter4.BaseQuickAdapter;
import com.chad.library.adapter4.QuickAdapterHelper;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.luck.picture.lib.utils.ToastUtils;
import com.student.db.AccountDao;
import com.student.db.AccountEntity;
import com.student.db.AppDatabase;
import com.student.db.PaymentEntity;
import com.student.db.PunchDao;
import com.student.db.PunchEntity;
import com.student.dms.databinding.ActivityComeOutHistoryBinding;
import com.student.dms.databinding.ItemAdminGoOutBinding;
import com.student.dms.databinding.ItemPaymentHistoryBinding;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ActivityAdminComeOutHistory extends BaseActivity {

    private ActivityComeOutHistoryBinding activityComeOutHistoryBinding;
    private BaseQuickAdapter<PunchEntity, VH> baseQuickAdapter;
    private AppDatabase roomDatabase;
    private AccountDao accountDao;
    private AccountEntity accountEntity;
    private PunchDao punchDao;
    private Date startDate;
    private Date endDate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityComeOutHistoryBinding = ActivityComeOutHistoryBinding.inflate(getLayoutInflater());
        setContentView(activityComeOutHistoryBinding.getRoot());
        activityComeOutHistoryBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(TitleBar titleBar) {
                finish();
            }
        });
        SharedPreferences sharedPreferences =getSharedPreferences("user", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("username", "");
        roomDatabase = DMSApplication.getApplication().getRoomDatabase();
        accountDao = roomDatabase.provideAccountDao();
        punchDao = roomDatabase.providePunchDao();
        Single<AccountEntity> accountFlow = accountDao.searchAccountByName(username);
        disposable.add(accountFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(accountEntity -> {
            this.accountEntity =accountEntity;
        }, studentFlowThrowable -> {
            ToastUtils.showToast(ActivityAdminComeOutHistory.this, "用户不存在，请注册！");
        }));
        activityComeOutHistoryBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(TitleBar titleBar) {
                finish();
            }
        });
        baseQuickAdapter = new BaseQuickAdapter<PunchEntity, VH>() {
            @NonNull
            @Override
            protected VH onCreateViewHolder(@NonNull Context context, @NonNull ViewGroup viewGroup, int i) {
                VH vh = new VH(ItemAdminGoOutBinding.inflate(LayoutInflater.from(context), viewGroup, false));
                return vh;
            }

            @Override
            protected void onBindViewHolder(@NonNull VH vh, int position, @Nullable PunchEntity itemData) {
                vh.itemViewBidnng.name.setText("姓名：       "+itemData.getName());
                vh.itemViewBidnng.roomNo.setText("寝室号：    "+itemData.getRoomNo());
                String type;
                if(itemData.getType()==1){
                    type="出寝";
                }else{
                    type="归寝";
                }
                vh.itemViewBidnng.type.setText("类型：       "+type);
                vh.itemViewBidnng.reason.setText("原因：       "+itemData.getReason());

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                String time = simpleDateFormat.format(itemData.getPunchTime());
                vh.itemViewBidnng.time.setText("打卡时间："+time);
            }
        };
        QuickAdapterHelper build = new QuickAdapterHelper.Builder(baseQuickAdapter).build();
        activityComeOutHistoryBinding.recyclerView.setAdapter(build.getAdapter());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ActivityAdminComeOutHistory.this);
        activityComeOutHistoryBinding.recyclerView.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(ActivityAdminComeOutHistory.this, DividerItemDecoration.VERTICAL);
        activityComeOutHistoryBinding.recyclerView.addItemDecoration(dividerItemDecoration);
        disposable.add(punchDao.getPunch().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
                    baseQuickAdapter.submitList(list);
                }, error -> {

                }
        ));

        //时间选择器
        TimePickerView startMaterialTimePicker = new TimePickerBuilder(ActivityAdminComeOutHistory.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                startDate=date;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm");
                String format = simpleDateFormat.format(date);
                activityComeOutHistoryBinding.startTimeTv.setText(format);
                //Toast.makeText(HolidayActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
            }
        })
                .setOutSideColor(getResources().getColor(R.color.color_00000000))
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("年","月","日","时","分",null).build();


        //  MaterialTimePicker endMaterialTimePicker = new MaterialTimePicker.Builder().setInputMode(INPUT_MODE_CLOCK).build();

        //时间选择器
        TimePickerView endMaterialTimePicker = new TimePickerBuilder(ActivityAdminComeOutHistory.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                endDate=date;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm");
                String format = simpleDateFormat.format(date);
                activityComeOutHistoryBinding.endTimeTv.setText(format);
                //Toast.makeText(HolidayActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
            }
        })
                .setOutSideColor(getResources().getColor(R.color.color_00000000))
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("年","月","日","时","分",null).build();



        activityComeOutHistoryBinding.startTimeSv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMaterialTimePicker.show();
            }
        });
        activityComeOutHistoryBinding.endTimeSv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endMaterialTimePicker.show();
            }
        });
        activityComeOutHistoryBinding.search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(startDate!=null && endDate!=null){
                    List<String> names = new ArrayList<>();
                    disposable.add(punchDao.searchPunch(startDate.getTime(),endDate.getTime()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
                        List<PunchEntity> collect = list.stream().filter(pushEntity -> {
                            boolean contains = names.contains(pushEntity.getName());
                            names.add(pushEntity.getName());
                            return !contains;
                        }).collect(Collectors.toList());
                        baseQuickAdapter.submitList(collect);
                            }, error -> {

                            }
                    ));
                }else{
                    ToastUtils.showToast(ActivityAdminComeOutHistory.this, "开始和结束时间不能为空！");
                }

            }
        });
    }


    static class VH extends RecyclerView.ViewHolder {
        @NonNull
        public ItemAdminGoOutBinding itemViewBidnng;

        public VH(@NonNull ItemAdminGoOutBinding itemViewBidnng) {
            super(itemViewBidnng.getRoot());
            this.itemViewBidnng = itemViewBidnng;
        }
    }
}
